package com.wu.creditmanager;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class WidgetUpdateService extends Service implements Runnable {

	public static final String ACTION_UPDATE_WIDGET = "com.wu.creditmanager.ACTION_UPDATE_WIDGET";
	private static final String TAG = "WidgetUpdateService";
	private static final long UPDATE_INTERVAL = 4 * 60 * 60 * 1000;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		new Thread(this).start();
	}

	// @Override
	// public int onStartCommand(Intent intent, int flags, int startId) {
	// int result = super.onStartCommand(intent, flags, startId);
	// new Thread(this).start();
	// return result;
	// }

	public void run() {
		AlarmListWidget.update(this);
		synchronized (AlarmListWidget.hasWidget) {
			if (!AlarmListWidget.hasWidget) {
				stopSelf();
				return;
			}
		}
		Intent updateIntent = new Intent(ACTION_UPDATE_WIDGET);
		updateIntent.setClass(this, WidgetUpdateService.class);
		PendingIntent pending = PendingIntent.getService(this, 0, updateIntent,
				0);
		long nowMillis = System.currentTimeMillis();
		long updateTime = nowMillis + UPDATE_INTERVAL;
		Log.i(TAG, "Widget next update at " + updateTime);
		AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		alarm.set(AlarmManager.RTC_WAKEUP, updateTime, pending);
		stopSelf();
	}
}
